﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class DuctAlignmentAndRoungBeam : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			if (commandData == null)
			{
				throw new NotImplementedException();
			}
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			Selection selection = activeUIDocument.Selection;
			List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(2);
			if (!YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			try
			{
				DuctRoundBeamForm ductRoundBeamForm = new DuctRoundBeamForm();
				if (ductRoundBeamForm.ShowDialog() != DialogResult.OK)
				{
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				else
				{
					viewTypes = YJKRevitTools.ListViewNeed(1);
					while (ductRoundBeamForm.nselType != 2 || YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
					{
						RevitVersionFuncs.ClearSelection(selection);
						string text = "风管升降与对齐";
						transaction = new Transaction(document, text);
						transaction.Start();
						new AlignmentDucts(document, selection).AlignDuctSet(ductRoundBeamForm.alignmentType, ductRoundBeamForm.isUserDate, ductRoundBeamForm.height, ductRoundBeamForm.nselType);
						transaction.Commit();
					}
					YJKMessageBox.Information("框选方式，仅支持平面操作！");
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				string message2 = ex.Message;
				if (RevitVersion.GetVersionNumber(document) == "2015" && message2.Contains("外部组件发生异常。"))
				{
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				else
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
			}
			finally
			{
				if (transaction != null && 1 == (int)transaction.GetStatus())
				{
					transaction.RollBack();
				}
			}
			return result;
		}
	}
}
